package com.zhiling.www.service;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhiling.www.entity.*;
import com.zhiling.www.feignclient.UserClient;
import com.zhiling.www.mapper.EntrustOrderMapper;
import com.zhiling.www.mapper.StockMapper;
import com.zhiling.www.mapper.WarehouseMapper;
import com.zhiling.www.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

@Service
public class EntrustOrderServiceImpl implements EntrustOrderService {

    private Logger logger = Logger.getLogger(EntrustOrderServiceImpl.class);
    @Autowired
    private EntrustOrderMapper entrustOrderMapper;
    @Autowired
    private StockMapper stockMapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private UserClient userClient;


    //买入股票，添加委托订单
    @Override
    @Transactional   //事务
    public Result addEntrustOrder(EntrustOrder entrustOrder, String token) {
        Result result = new Result();
        //解析token，获取用户id
        Claims claims = JwtUtils.parseToken(token);
        int userId = Integer.parseInt(String.valueOf(claims.get("userId")));
        //添加委托订单
        entrustOrder.setoStatus(0);
        entrustOrder.setoStockType(0);
        entrustOrder.setoStockUid(userId);
        Date time = new Date();
        entrustOrder.setoEntrusttime(time);
        //比较委托价格和当前价格,如果委托价格大于当前价格，则立即成交
        Stock stock = stockMapper.selectByPrimaryKey(entrustOrder.getoStockCode());
        if (entrustOrder.getoStockPrice() >= stock.getNowprice()) {
            entrustOrder.setoStatus(1);
            //添加用户持仓信息
            //判断仓库中是否有该股票
            Example example = new Example(Warehouse.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("wareUserid", userId);
            criteria.andEqualTo("wareStockcode", entrustOrder.getoStockCode());
            Warehouse warehouse = warehouseMapper.selectOneByExample(example);
            //不存在 则添加一列
            if (warehouse == null) {
                warehouse = new Warehouse();
                warehouse.setWareUserid(userId);
                warehouse.setWareStockcode(entrustOrder.getoStockCode());
                warehouse.setWareStockname(entrustOrder.getoStockName());
                warehouse.setWareStocknum(entrustOrder.getoStockNum());
                warehouse.setWareStockcost(entrustOrder.getoStockPrice());
                warehouse.setWareStockprice(stock.getNowprice());
                int insert = warehouseMapper.insert(warehouse);
            } else {  //存在 则修改此列
                //logger.debug(warehouse);
                //计算成本
                double costPrice =
                        (warehouse.getWareStocknum() * 100 * warehouse.getWareStockcost() + entrustOrder.getoStockNum() * 100 * entrustOrder.getoStockPrice())
                                / (warehouse.getWareStocknum() * 100 + entrustOrder.getoStockNum() * 100);
                costPrice = (double) Math.round(costPrice * 1000) / 1000;
                warehouse.setWareStockcost(costPrice);
                warehouse.setWareStocknum(entrustOrder.getoStockNum() + warehouse.getWareStocknum());
                int i = warehouseMapper.updateByPrimaryKeySelective(warehouse);
            }
            //委托订单提交，更新余额信息
            Result resultUser = userClient.findUser(userId);
            String stringUser = JSON.toJSONString(resultUser.getData());
            User user = JSON.parseObject(stringUser, User.class);
            user.setUserMoney(user.getUserMoney() - entrustOrder.getoStockNum() * 100 * entrustOrder.getoStockPrice());
            Result resultUpdateMoney = userClient.updateMoney(user);
        }
        int i = entrustOrderMapper.insert(entrustOrder);
        if (i > 0) {
            result.setCode(200);
            result.setMsg("委托提交成功");
            return result;
        }
        result.setCode(400);
        result.setMsg("委托提交失败");
        return result;
    }

    //卖出股票，添加委托订单
    @Transactional  //事务
    @Override
    public Result addSellEntrustOrder(EntrustOrder entrustOrder, String token) {
        Result result = new Result();
        //解析token，获取用户id
        Claims claims = JwtUtils.parseToken(token);
        int userId = Integer.parseInt(String.valueOf(claims.get("userId")));
        //添加委托订单
        entrustOrder.setoStatus(0);
        entrustOrder.setoStockType(1);
        entrustOrder.setoStockUid(userId);
        Date time = new Date();
        entrustOrder.setoEntrusttime(time);
        //比较委托价格和当前价格,如果委托价格小于当前价格，则立即成交
        Stock stock = stockMapper.selectByPrimaryKey(entrustOrder.getoStockCode());
        if (entrustOrder.getoStockPrice() <= stock.getNowprice()) {
            entrustOrder.setoStatus(1);
            //减少用户持仓
            Warehouse warehouse = new Warehouse();
            warehouse.setWareStockcode(entrustOrder.getoStockCode());
            warehouse.setWareUserid(userId);
            Warehouse warehouseSelect = warehouseMapper.selectOne(warehouse);
            int num = warehouseSelect.getWareStocknum() - entrustOrder.getoStockNum();
            if(num > 0){
                warehouseSelect.setWareStocknum(warehouseSelect.getWareStocknum() - entrustOrder.getoStockNum());
                int i = warehouseMapper.updateByPrimaryKey(warehouseSelect);
            }else { //如果该股持仓为零，则删除该持仓信息
                int i = warehouseMapper.deleteByPrimaryKey(warehouseSelect.getWareId());
            }
            //委托订单成交，更新余额信息
            Result resultUser = userClient.findUser(userId);
            String stringUser = JSON.toJSONString(resultUser.getData());
            User user = JSON.parseObject(stringUser, User.class);
            user.setUserMoney(user.getUserMoney() + entrustOrder.getoStockNum() * 100 * entrustOrder.getoStockPrice());
            Result resultUpdateMoney = userClient.updateMoney(user);
        }
        int i = entrustOrderMapper.insert(entrustOrder);
        if (i > 0) {
            result.setCode(200);
            result.setMsg("委托提交成功");
            return result;
        }
        result.setCode(400);
        result.setMsg("委托提交失败");
        return result;
    }


    //分页加载委托订单
    @Override
    public Result orderList(int page, int pageSize, int status, String token) {
        Result result = new Result();
        //解析token，获取用户id
        Claims claims = JwtUtils.parseToken(token);
        int userId = Integer.parseInt(String.valueOf(claims.get("userId")));
        PageHelper.startPage(page, pageSize);
        Example example = new Example(EntrustOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("oStockUid", userId);
        if (status != -1) {
            criteria.andEqualTo("oStatus", status);
        }
        example.setOrderByClause("o_entrustTime desc");
        List <EntrustOrder> entrustOrders = entrustOrderMapper.selectByExample(example);
        Page <EntrustOrder> plist = (Page <EntrustOrder>) entrustOrders;
        PageBean <EntrustOrder> pb = new PageBean <>(
                plist.getPageNum(),
                plist.getTotal(),
                plist.getPageSize(),
                plist.getPages(),
                plist.getResult()
        );
        result.setCode(200);
        result.setData(pb);
        return result;
    }

    //撤单
    @Override
    public Result cancelOrder(int oid) {
        Result result = new Result();
        EntrustOrder entrustOrder = new EntrustOrder();
        entrustOrder.setOid(oid);
        entrustOrder.setoStatus(2);
        int i = entrustOrderMapper.updateByPrimaryKeySelective(entrustOrder);
        if (i > 0) {
            result.setCode(200);
            result.setMsg("成功撤单");
            return result;
        }
        result.setCode(400);
        result.setMsg("撤单失败");
        return result;
    }
}
